package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询新建或未分配的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求
     *      两种情况：
     *          1、合并采购需求时指定采购单
     *          2、合并采购需求时未指定采购单
     *              需要新创建一个采购单
     * @param mergeVo
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //如果没有指明采购单，那么默认是新建一个采购单
        if(purchaseId ==null){
            PurchaseEntity purchaseEntity=new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }
        //TODO 确认采购单状态是0或1才可以合并，即采购单是创建或已分配状态
        //所有采购需求
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        //更新采购需求的采购单id和采购需求的状态
        purchaseDetailService.updateBatchById(detailEntities);
        //合并采购单后，要更新采购单的修改时间
        PurchaseEntity purchaseEntity=new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 员工领取采购单
     * @param ids
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //1、过滤出当前采购单是新建或已分配状态
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(entity -> {
            if (entity.getStatus() == 0 || entity.getStatus() == 1) {
                return true;
            } else {
                return false;
            }
        }).map(item ->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2、改变采购单的状态和修改时间
        this.updateBatchById(purchaseEntityList);
        //3、改变采购单对应的采购项的状态
        purchaseEntityList.forEach(item -> {
            //获取采购单对应的采购需求
           List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchase(item.getId());
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailEntities.stream().map(detailEntity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(detailEntity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            //更新采购需求的状态为正在采购
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });
    }

    /**
     * 完成采购
     * @param vo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo vo) {
        Long id = vo.getId();
        //1、改变采购项的状态
        List<PurchaseItemDoneVo> items = vo.getItems();
        //收集要更新的采购需求
        List<PurchaseDetailEntity> updates=new ArrayList<>();
        //采购成功标志位
        boolean flag=true;
        //遍历采购项，分离采购成功和采购不成功的采购项
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity=new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //采购失败
                flag=false;
                //设置采购需求为采购失败
                detailEntity.setStatus(item.getStatus());
                //TODO 添加采购失败原因，但是数据库现在并没有原因这个字段，可以自己添加,失败也分为全量失败或只采购一部分
            }else {
                //设置采购成功信息
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //2、将成功采购的商品进行入库
                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        //批量更新采购项的状态
        purchaseDetailService.updateBatchById(updates);
        //3、改变采购单的状态，如果有一个采购项采购失败，那么采购单的状态就是异常的
        PurchaseEntity purchaseEntity=new PurchaseEntity();
        purchaseEntity.setId(vo.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}